import { View, Image } from '@tarojs/components'
import { chooseImage, showToast } from '@tarojs/taro'
import { memo } from 'react'
import { PhotoOutlined, DeleteOutlined } from '@taroify/icons'
import { formContextProvider } from '../BtForm/formContextProvider';
import Validator from '../BtForm/validator';
import './index.scss'

interface BtUploadProps {
  /** 图片地址 */
  value?: string
  /** 是否禁用 */
  disabled?: boolean
  /** 图片大小限制，单位MB */
  maxSize?: number
  /** 值变化事件 */
  onChange?: (value: string) => void
  /** 自定义类名 */
  className?: string
  prop?: string
}

function BtUpload({
  value = '',
  disabled = false,
  maxSize = 10,
  onChange,
  className = '',
  prop = ''
}: BtUploadProps) {
  const [state] = formContextProvider.useTracked()

  const validFormItem = async (inputValue) => {
    const rule = {}
    const field = state.fields.find(item => item.prop === prop)
    if (!field) return
    if (state.rules[prop]) {
      rule[prop] = state.rules[prop]
    }
    const validator = new Validator(rule)
    const errs = await validator.validate({ [prop]: inputValue })
    const msg = (errs && errs[0].message) || ''
    field.setErrMsg(msg)
  }

  // 选择图片
  const handleChoose = async () => {
    if (disabled) return

    try {
      const res = await chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      // 检查文件大小
      const file = res.tempFiles[0]
      if (file.size > maxSize * 1024 * 1024) {
        showToast({
          title: `图片大小不能超过${maxSize}MB`,
          icon: 'none'
        })
        return
      }

      // TODO: 上传图片到服务器
      const imageUrl = res.tempFilePaths[0]
      validFormItem(imageUrl)
      onChange?.(imageUrl)

    } catch (error) {
      console.log('选择图片失败:', error)
    }
  }

  // 删除图片
  const handleDelete = (e: any) => {
    e.stopPropagation()
    if (disabled) return
    validFormItem('')
    onChange?.('')
  }

  return (
    <View
      className={`bt-upload ${className}`}
      onClick={handleChoose}
    >
      {value ? (
        <View className='bt-upload__preview'>
          <Image
            className='bt-upload__image'
            src={value}
            mode='aspectFill'
          />
          {!disabled && (
            <View className='bt-upload__delete' onClick={handleDelete}>
              <DeleteOutlined />
            </View>
          )}
        </View>
      ) : (
        <View className='bt-upload__placeholder'>
          <PhotoOutlined className='bt-upload__icon' />
          <View className='bt-upload__text'>上传图片</View>
        </View>
      )}
    </View>
  )
}

export default memo(BtUpload)
